# In this script we estimate the market yield curve based on the prices of a set of bonds
# which constitute our market assumptions. 

library(FinancialMath)
library(tidyverse)
library(readxl)
market.assumption <- read_xlsx(
  "Examples/interestRateData2026.xlsx", sheet = "marketAssumptions31.08.2026"
) 
market.assumption

payments.tbl <- read_xlsx(
  "Examples/interestRateData2026.xlsx", sheet = "paymentMatrixC"
  )
C <- as.matrix(payments.tbl)
C

####### Part 1 - Set up our example ##########

#  We will set our bond prices according to a certain yield curve (so that after we
# use replication to get that exact yield)

# Net present value of the first bond (which is the price P_1 of our first bond)
NPV(
  cf0 = 0,
  # cashflow of the bond in line j
  cf = as.numeric(C[1,]),
  times = 1:12,
  # 
  i = market.assumption$`Average yield_annual`[[1]] 
)


# "Clean" Market price - Net Present Value of all 12 bonds in our market assumptions
n <- 12
npv.list <- vector(mode = "list", length = n)
for(j in 1:12){
  
  npv.list[[j]] <- NPV(
    cf0 = 0,
    # cashflow of the bond in line j
    cf = as.numeric(C[j,]),
    times = 1:n,
    # 
    i = market.assumption$`Average yield_annual`[[j]] 
  )
  
}
npv.list

# flatten_dbl transforms the list in a vector of real numbers (data type "double")
flatten_dbl(npv.list)

market.assumption <- market.assumption %>% 
  mutate(`market price B` = flatten_dbl(npv.list))
market.assumption

# # This also works, in spite of being less effective computationally
# n <- 15
# 
# x <- c()
# 
# for (j in 1:n){
# 
#   x <- c(x,
#          NPV(
#            cf0 = 0,
#            # cashflow of the bond in line j
#            cf = as.numeric(C[j,]),
#            times = 1:n,
#            #
#            i = market.assumption$`Average yield_annual`[[j]]
#          )
#   )
# 
# }
# 
# market.assumption <- market.assumption %>%
#   mutate(`market price B` = flatten_dbl(npv.list))
# market.assumption

############## Determine the yield by Replication ##########

# Let us get the implicit yield by replication of bond prices and verify that
# it is the one we used to set up the example.

# The market yield curve - continuous compounding
market.yield.curve <- data.frame(t = 1:n) %>% 
  mutate(
    # P(t) = C^(-1)B # Obviously, this does not work...
    P_t = as.numeric(solve(C) %*% market.assumption$`market price B`),
    # Finally, the yield curve
    y_t.cont = -log(P_t) / t,
    y_t.annual = exp(y_t.cont) - 1
    )
solve(C) %>% View
market.yield.curve

save(market.yield.curve, file = "Examples/market.yield.curve.Rdata")

library(writexl)
write_xlsx(market.yield.curve, path = "Examples/market.yield.curve.xlsx")


